<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      :action="uploadUrl"
      :data="uploadData"
      :auto-upload="false"
      :on-change="handleChange"
      :on-error="handleError"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
      list-type="picture"
      :show-file-list="false"
      v-bind="$attrs"
      v-on="$listeners"
      accept="image/jpeg,image/gif,image/png"
    >
      <el-button size="small" type="success" :icon="uploadIcon">{{
        uploadLabel
      }}</el-button>
      <slot name="tip" slot="tip"></slot>
      <div slot="tip" class="el-upload__tip">{{ uploadTip }}</div>
      <div v-if="uploadMessage">{{ uploadMessage }}</div>
    </el-upload>
    <CropperDialog
      v-if="showCropper"
      :visible.sync="cropperVisible"
      :cropper-img="cropperImg"
      @upload-img="uploadImg"
      :is-wx-upload="isWxUpload"
    />
    <div v-if="loading || imgSrc || wxShowImg" class="display">
      <div v-if="loading">加载了{{ percentage }}%</div>
      <img style="width: 100%" v-if="imgSrc && !isWxUpload" :src="imgSrc" />
      <img
        style="width: 100%"
        v-if="wxShowImg && isWxUpload"
        :src="wxShowImg"
      />
      <el-button
        class="delete-btn"
        v-if="imgSrc"
        @click="handleRemove"
        type="warning"
        >删除</el-button
      >
    </div>
  </div>
</template>
<script>
import CropperDialog from '@/components/CropperDialog'
import http from '@/utils/http'
export default {
  name: 'hycFormUpload',
  components: { CropperDialog },
  inheritAttrs: false,
  //  inject:['form'],
  model: {
    prop: 'value',
  },
  props: {
    value: {
      type: String,
      default: '',
    },
    uploadData: {
      type: Object,
      default: null,
    },
    uploadUrl: {
      type: String,
      default: '/file-management/file/upload',
    },
    downloadUrl: {
      type: String,
      default: '/file-management/file/download',
    },
    uploadLabel: {
      type: String,
      default: '上传图片',
    },
    uploadTip: {
      type: String,
      default: '',
    },
    uploadIcon: {
      type: String,
      default: 'el-icon-upload2',
    },
    showCropper: {
      type: Boolean,
      default: false,
    },
    isWxUpload: {
      type: Boolean,
      defualt: false,
    },
    submitUserId: {
      type: Number,
      default: -1,
    },
  },
  data() {
    return {
      loading: false,
      uploadMessage: '',
      cropperVisible: false,
      cropperImg: '',
      fileList: null,
      percentage: 0,
      imgSrc: '',
      wxShowImg: '',
    }
  },
  watch: {
    value: {
      handler(val, oldVal) {
        if (val && val != oldVal) {
          this.imgSrc =
            process.env.VUE_APP_BASE_URL_API +
            (this.downloadUrl ? this.downloadUrl : '/file/img') +
            '?fileId=' +
            val
        }
      },
      immediate: true,
    },
  },
  methods: {
    dispatch(componentName, eventName, params) {
      var parent = this.$parent || this.$root
      var name = parent.$options.componentName

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent

        if (parent) {
          name = parent.$options.componentName
        }
      }
      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params))
      }
    },
    setCurrentValue(value) {
      let val
      if (this.isWxUpload) {
        val = value.media_id
      } else {
        val = value
      }
      this.$emit('input', val)
      this.dispatch('ElFormItem', 'el.form.change', [].concat(val))
    },
    uploadImg(file) {
      this.uploadFile = file
      this.$refs.upload.submit()
      this.cropperVisible = false
    },
    openCropper(file) {
      var reader = new FileReader()
      reader.onload = (e) => {
        let data
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        this.cropperImg = data
      }
      // 转化为base64
      // 转化为blob
      if (this.isWxUpload) {
        reader.readAsDataURL(file)
      } else {
        reader.readAsArrayBuffer(file)
      }
      this.showCropper ? (this.cropperVisible = true) : this.uploadImg(file)
    },
    httpRequest(request) {
      this.loading = true
      const { action, data } = request
      let formData = new FormData()
      if (this.isWxUpload) {
        this.uploadFile = new window.File([this.uploadFile], 'uploadImg.jpg', {
          type: 'image/png',
        })
      }
      for (let key in data) {
        formData.append(key, data[key])
      }
      formData.append('file', this.uploadFile)

      return http
        .request({
          method: 'post',
          url: action,
          data: formData,
          onUploadProgress: (progressEvent) => {
            this.percentage = (progressEvent.loaded / progressEvent.total) * 100
          },
        })
        .then((res) => {
          this.loading = false
          this.uploadMessage = ''
          this.setCurrentValue(res)

          if (this.isWxUpload) {
            var reader = new FileReader()

            reader.onload = (e) => {
              this.wxShowImg = e.target.result
            }

            reader.readAsDataURL(this.uploadFile)
          }
        })
    },
    handleChange(file, fileList) {
      if (file.status !== 'ready') return
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
      const { raw } = file
      this.openCropper(raw)
    },
    // handleSuccess(res) {
    //   this.loading = false
    //   this.uploadMessage = ''
    //   if (res.code === 1) {
    //     let fileId = res.fileId
    //     let value = fileId
    //       ? process.env.VUE_APP_BASE_URL_API +
    //         (this.downloadUrl ? this.downloadUrl : '/file/img') +
    //         '?fileId=' +
    //         fileId +
    //         'X'
    //       : null
    //     this.setCurrentValue(value)
    //   }
    // },
    handleRemove() {
      this.uploadMessage = ''
      this.imgSrc = ''
      if (this.isWxUpload) {
        this.wxShowImg = null
      }
      this.percentage = 0
      this.setCurrentValue('')
    },
    handleError() {
      this.loading = false
      // if (file && file.size > 2097152) {
      //   this.uploadMessage = '上传文件失败，上传文件请选择2M以下文件!'
      // } else {
      //   this.uploadMessage = '上传文件失败，上传文件请选择2M以下文件!'
      // }
      this.setCurrentValue('')
    },
    beforeUpload() {
      this.loading = true
    },
  },
}
</script>
<style lang="scss" scoped>
.display {
  width: 100%;
  border: 1px solid #d6d8e0;
  min-height: 200px;
  max-width: 300px;
  position: relative;
  text-align: center;
  padding-top: 20px;
  .delete-btn {
    left: 0;
    bottom: 0;
    position: absolute;
    border-radius: 0 !important;
  }
}
</style>
